#!/bin/bash /etc/rc.common

START=83
STOP=83

USE_PROCD=1
PROG=/usr/bin/ootocCLI

_info() {
    logger -p daemon.info -t "ootoc" "$*"
}

_err() {
    logger -p daemon.err -t "ootoc" "$*"
}

init_conf() {
    config_load "ootoc"

    local LOG
    config_get LOG log path

	[ -d "/etc/opkg/" ] || mkdir -p "/etc/opkg/" 2>/dev/null
	[ -e "/etc/opkg/distfeeds.conf" ] || touch "/etc/opkg/distfeeds.conf"

	# backup opkg feeds conf
	FEEDS="/etc/opkg/distfeeds.conf"
	FEEDS_BAK="${FEEDS}.bak"
	[ -d "${FEEDS%/*}" ] || mkdir -p "${FEEDS%/*}" 2>/dev/null
	[ -e "$FEEDS_BAK" ] || {
		_err "opkg feeds backup not exist '$FEEDS_BAK', backup now..."
		[ -e "$FEEDS" ] || {
			_err "not exist file: $FEEDS"
			return 1
		}
		cp -rf "$FEEDS" "$FEEDS_BAK"
	}

	# create log path
	[ -d "${LOG%/*}" ] || mkdir -p "${LOG%/*}" 2>/dev/null

	# disable signature
	[ -e /etc/opkg.conf ] || {
		_err "not exist file: /etc/opkg.conf"
		return 1
	}
	sed -i "s/^[ ]*option check_signature/# option check_signaturesign/" /etc/opkg.conf
	return 0
}

start_service() {
	config_load "ootoc"

	local ENABLED ADDR PORT TAR_URL PROXY_ENABLED PROXY_ADDR LOG
	config_get ENABLED global enabled
	config_get ADDR server addr
	config_get PORT server port
	config_get TAR_URL server tar_url
	config_get AUX_URL server aux_url
	config_get PROXY_ENABLED proxy enabled
	config_get PROXY_ADDR proxy proxy_addr
	config_get LOG log path

	[[ $ENABLED == 0 ]] && {
		_info "Instance 'ootoc' disabled."
		return 1
	}
	_info "Instance 'ootoc' enabled."
    init_conf || return 1;

	# _info "$PROG server  --log \"$LOG\" --addr \"$ADDR\" --port \"$PORT\" --tar-url \"$TAR_URL\" --aux-url \"$AUX_URL\" --subscription \"/etc/opkg/distfeeds.conf\""
    procd_open_instance
    procd_set_param command $PROG server
	procd_append_param command --log "$LOG"
	procd_append_param command --addr "$ADDR"
	procd_append_param command --port "$PORT"
	procd_append_param command --tar-url "$TAR_URL"
	procd_append_param command --aux-url "$AUX_URL"
	procd_append_param command --subscription "/etc/opkg/distfeeds.conf"
	[[ $PROXY_ENABLED == 1 ]] && {
		procd_set_param env all_proxy="$PROXY_ADDR" https_proxy="$PROXY_ADDR" http_proxy="$PROXY_ADDR"
		procd_set_param env ALL_PROXY="$PROXY_ADDR" HTTPS_PROXY="$PROXY_ADDR" HTTP_PROXY="$PROXY_ADDR"
	}
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_set_param file /etc/config/ootoc
	procd_set_param pidfile /var/run/ootoc.pid
	procd_set_param respawn retry=60
	procd_close_instance
}

stop_service()
{
    service_stop ${PROG}
}

service_triggers()
{
    procd_add_reload_trigger "ootoc"
}
